package com.road.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.road.model.Msg;
import com.road.utils.Consists;
import com.road.utils.ResponseUtil;
import com.road.utils.VerifyCome;

/**
 * Servlet Filter implementation class VerfifyFrom
 */
//@WebFilter(description = "验证请求来源", urlPatterns = { "/*" })
public class VerfifyFrom implements Filter {

    /**
     * Default constructor. 
     */
    public VerfifyFrom() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
        Map<String, Object> map = VerifyCome.fromOurApp((HttpServletRequest)request);
        if((boolean) map.get(VerifyCome.KEY_OK)) {
        	chain.doFilter(request, response);
        }else {
        	List<Object> list=new ArrayList<>();
        	Msg msg=new Msg();
        	msg.setCode(Consists.Error_Code_FAIL);
        	msg.setMsg(map.get(VerifyCome.KEY_FORM).toString());
        	list.add(msg);
        	ResponseUtil.sendScript((HttpServletResponse)response, JSON.toJSONString(list));
        }
		
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
